import { ref } from 'vue'

export function useRecorder() {
  // 录音状态
  const isRecording = ref(false)
  // 录音实例
  const mediaRecorder = ref(null)
  // 录音数据
  const audioData = ref(null)
  // 错误信息
  const error = ref(null)

  // 开始录音
  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      mediaRecorder.value = new MediaRecorder(stream)
      const chunks = []

      mediaRecorder.value.ondataavailable = (e) => {
        chunks.push(e.data)
      }

      mediaRecorder.value.onstop = () => {
        const blob = new Blob(chunks, { type: 'audio/webm' })
        audioData.value = URL.createObjectURL(blob)
        // 停止所有音轨
        stream.getTracks().forEach(track => track.stop())
      }

      mediaRecorder.value.start()
      console.log(';---')
      isRecording.value = true
      error.value = null
    } catch (err) {
      error.value = err.message
      console.error('录音失败:', err)
    }
  }

  // 停止录音
  const stopRecording = () => {
    if (mediaRecorder.value && isRecording.value) {
      mediaRecorder.value.stop()
      isRecording.value = false
    }
  }

  // 播放录音
  const playRecording = () => {
    if (audioData.value) {
      const audio = new Audio(audioData.value)
      audio.play()
    }
  }

  // 下载录音
  const downloadRecording = () => {
    if (audioData.value) {
      const a = document.createElement('a')
      a.href = audioData.value
      a.download = `recording-${Date.now()}.webm`
      a.click()
    }
  }

  return {
    isRecording,
    audioData,
    error,
    startRecording,
    stopRecording,
    playRecording,
    downloadRecording
  }
}